package com.waidi.clothespad.fragment;

import android.app.Fragment;
import android.content.Context;
import android.graphics.drawable.ColorDrawable;
import java.text.SimpleDateFormat;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.TableLayout;
import android.widget.TableRow;
import android.widget.TextView;

import com.waidi.clothespad.R;
import com.waidi.clothespad.common.Config;
import com.waidi.clothespad.common.DpsOrderInfo;
import com.waidi.clothespad.common.MessageToUi;
import com.waidi.clothespad.common.MyToast;
import com.waidi.clothespad.common.WorkerProductInfo;
import com.waidi.clothespad.ui.WaitDialog;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.Date;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * Created by Administrator on 2017/4/26.
 */

public class FragShengchantongji extends Fragment {
    private static final String TAG = "FragShengchantongji";
    @BindView(R.id.ll_shaixuan)
    LinearLayout llShaixuan;
    @BindView(R.id.tablelayout_id)
    TableLayout tablelayout;

    @BindView(R.id.tv_product_id)
    TextView tv_product;

    @BindView(R.id.tv_product_num_id)
    TextView tv_product_num;



    Unbinder unbinder;
    private View view;
    public Context context;

    PopupWindow popupWindow;
    LayoutInflater inflater;

    WorkerProductInfoHandler handler =null;
    ArrayList<WorkerProductInfo> workerProductInfoArrayList = null;
    private boolean onDetach = false;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        view = inflater.inflate(R.layout.frag_worker_product_info, container, false);
        handler = new WorkerProductInfoHandler();
        onDetach = false;
        unbinder = ButterKnife.bind(this, view);
        return view;
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        context = getActivity();
        initParam();
        initElem();
        initTableLayoutView();
        initWaitDialog();
        onDetach = false;
    }
    private void initWaitDialog()
    {
        waitDialog = new WaitDialog(context);
        waitDialog.setText("正在提交...");
    }
    private static int choose_tag = 1;
    private WaitDialog waitDialog =null;
    public void initParam() {


        workerProductInfoArrayList = new ArrayList<>();

        inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View contentview = inflater.inflate(R.layout.layer_shaixuan_shengchan_query, null);




        final RadioButton radioButtonToday = (RadioButton)contentview.findViewById(R.id.today);
        final RadioButton radioButtonWeek = (RadioButton)contentview.findViewById(R.id.this_week);
        final RadioButton radioButtonLastWeek = (RadioButton)contentview.findViewById(R.id.last_week);
        final RadioButton radioButtonMonth = (RadioButton)contentview.findViewById(R.id.this_month);
        final RadioButton radioButtonLastMonth = (RadioButton)contentview.findViewById(R.id.last_month);
        final RadioButton radioButtonNextWeek = (RadioButton)contentview.findViewById(R.id.future_week);



        final RadioGroup radioGroup = (RadioGroup)contentview.findViewById(R.id.radiogroup);

        radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                if(checkedId==radioButtonToday.getId())
                {
                    choose_tag = 1;
                    tv_product.setText("本日生产");

                }else  if(checkedId==radioButtonWeek.getId())
                {
                    choose_tag = 2;
                    tv_product.setText("本周生产");
                }else
                if(checkedId==radioButtonLastWeek.getId())
                {
                    choose_tag = 3;
                    tv_product.setText("上周生产");
                }else if(checkedId==radioButtonMonth.getId())
                {
                    choose_tag = 4;
                    tv_product.setText("本月生产");
                }
                else if(checkedId==radioButtonLastMonth.getId())
                {
                    choose_tag = 5;
                    tv_product.setText("上月生产");
                }
                else if(checkedId==radioButtonNextWeek.getId())
                {
                    choose_tag = 6;
                    tv_product.setText("未来7天计划生产");
                }else
                {
                    choose_tag = 1; //default
                    tv_product.setText("本日生产");
                }
            }
        });


        Button bt_ok = (Button) contentview.findViewById(R.id.btn_confirm);

        bt_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                Config A = new Config(context);
                Config.DpsInterface dpsInterface = A.new DpsInterface(Config.devConfig.web_addr);
                String url = dpsInterface.workerproduct + "&dayType=" +choose_tag;
                getWorkProductInfo(url);

            //popupWindow.dismiss();
            }
        });


        Button bt_cancle = (Button) contentview.findViewById(R.id.btn_cancel);
        bt_cancle.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                popupWindow.dismiss();
            }
        });




        contentview.setFocusable(true);
        contentview.setFocusableInTouchMode(true);
        popupWindow = new PopupWindow(contentview, ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
        popupWindow.setFocusable(true);
        popupWindow.setBackgroundDrawable(new ColorDrawable(0x00005511));
        popupWindow.setBackgroundDrawable(new ColorDrawable());

    }

    public void initElem() {


        llShaixuan.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                popupWindow.showAtLocation(view,  Gravity.RIGHT, 0, 0);
            }
        });
        //addTableLayoutView();
    }

    public void initTableLayoutView()
    {

    }

    public void clearTableLayoutView()
    {
        int count = tablelayout.getChildCount();
        Log.i(TAG,"清空行数："+count);
        for(int i=count;i>=0;i--)
        {
            tablelayout.removeView(tablelayout.getChildAt(i));//必须从后面减去子元素
        }
    }

    public void addTableLayoutView()
    {

    /*
        WorkerProductInfo tmp = new WorkerProductInfo();
        tmp.workername  = "111";
        tmp.workernum = "001";
        tmp.orderid = "order00001";
        tmp.stylenum = "style00001";
        tmp.qty = "1000";
        tmp.bad_qty = "50";

        tmp.lineNum = "1101";
        tmp.station = "02";
        tmp.processName = "封口袋，扯线";
        tmp.workDate = "20190809";
        workerProductInfoArrayList.add(tmp);
        workerProductInfoArrayList.add(tmp);
        workerProductInfoArrayList.add(tmp);
        workerProductInfoArrayList.add(tmp);*/


        int len = workerProductInfoArrayList.size();
        tv_product_num.setText("");
        tv_product_num.setText(len+"条记录");

        clearTableLayoutView();
        for(int i=0;i<len;i++)
        {
            View selectView = View.inflate(context, R.layout.workerinfotablerow, null);
            LinearLayout ll = (LinearLayout)selectView;
            TableRow tableRow = (TableRow)ll.getChildAt(0);

            if(tableRow.getChildCount()>=5) {
                ((TextView) tableRow.getChildAt(0)).setText(Integer.toString(i));
                ((TextView) tableRow.getChildAt(1)).setText(workerProductInfoArrayList.get(i).orderid+"/"+workerProductInfoArrayList.get(i).stylenum);
             //   ((TextView) tableRow.getChildAt(2)).setText();
                ((TextView) tableRow.getChildAt(2)).setText(workerProductInfoArrayList.get(i).processName);



                ((TextView) tableRow.getChildAt(3)).setText(workerProductInfoArrayList.get(i).qty+"/"+workerProductInfoArrayList.get(i).bad_qty);
               // ((TextView) tableRow.getChildAt(5)).setText(workerProductInfoArrayList.get(i).bad_qty);
                ((TextView) tableRow.getChildAt(4)).setText(workerProductInfoArrayList.get(i).workername+"/"+workerProductInfoArrayList.get(i).workernum);
                //((TextView) tableRow.getChildAt(7)).setText(workerProductInfoArrayList.get(i).workernum);
               ((TextView) tableRow.getChildAt(5)).setText(workerProductInfoArrayList.get(i).lineNum);
                ((TextView) tableRow.getChildAt(6)).setText(workerProductInfoArrayList.get(i).workDate);

            tablelayout.addView(selectView);
            }
        }
        int count = tablelayout.getChildCount();
        Log.i(TAG,"行数："+count);

    }

    private void getWorkProductInfo(final String url)
    {
        if(Config.rfidWorkerInfo.workernum.length()==0)
        {
            MyToast.showToast(context,"请先刷卡登录?");
            return;
        }
        getWorkProductInfoThread thread = new getWorkProductInfoThread(handler,context,url);
        waitDialog.show();//loading......
        thread.start();
    }

    public class getWorkProductInfoThread extends Thread {
        public Context context0 = null;
        public Handler handler0 = null;
        public String Url = null;

        public getWorkProductInfoThread(Handler handlerin, Context contextin, String url) {
            handler0 = handlerin;
            context0 = contextin;
            Url = url;
        }
        public void run()
        {

            String result = "";
            HttpClient httpCient = new DefaultHttpClient();
            httpCient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT,4000);//连接时间
            httpCient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT,2000);//数据传输时间
            try
            {
                HttpGet httpGet = new HttpGet(Url);

                int code = -1;

                Log.i(TAG, Url);
                HttpResponse response = httpCient.execute(httpGet);
                code = response.getStatusLine().getStatusCode();
                Log.i(TAG, "get server reponse code: "+Integer.toString(code));
                waitDialog.dismiss();
                if (response.getStatusLine().getStatusCode() == 200)
                {
                    HttpEntity entity = response.getEntity();
                    result = EntityUtils.toString(entity, HTTP.UTF_8);
                    Log.i(TAG, result);
                    try {

                        JSONObject jsonObj = new JSONObject(result);
                        if (jsonObj == null)
                            return;

                        if(jsonObj.has("error")==true)
                        {
                            Log.i(TAG,"获取员工生产信息错误！！");
                            JSONObject error =  jsonObj.optJSONObject("error");
                            String message = error.optString("message");
                            String s = "获取员工生产信息错误："+message;
                            new MessageToUi().send(23,"exception",s,handler0);
                        }
                        else
                        {
                            if(jsonObj.has("data")==true) {
                                JSONArray array0 = jsonObj.optJSONArray("data");
                                int len = array0.length();
                                String str=String.format("获取到%s条员工生产信息", len);
                                Log.i(TAG, str);
                                workerProductInfoArrayList.clear();
                                for(int i=0;i<array0.length();i++)
                                {
                                    WorkerProductInfo tmp = new WorkerProductInfo();

                                    JSONObject obj= (JSONObject)array0.opt(i);
                                    tmp.workername  = obj.optString("name");
                                    tmp.workernum = obj.optString("workNum");
                                    tmp.orderid = obj.optString("po");
                                    tmp.stylenum = obj.optString("styNum");
                                    tmp.qty = Integer.toString(obj.optInt("regularQty"));
                                    tmp.bad_qty = Integer.toString(obj.optInt("defectQty"));

                                    tmp.lineNum = obj.optString("lineNum");
                                    tmp.station = obj.optString("station");
                                    tmp.processName = obj.optString("processName");

                                    long lt = (obj.optLong("workDate"));
                                    Date date = new Date(lt);

                                    SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMdd");
                                    tmp.workDate = simpleDateFormat.format(date);

                                    workerProductInfoArrayList.add(tmp);

                                }
                                new MessageToUi().send(1,"info",str,handler0);
                            }

                        }
                    }
                    catch (JSONException e)
                    {
                        e.printStackTrace();
                        new MessageToUi().send(23,"exception",e.toString(),handler0);
                    }
                }
                else
                {
                    Log.i(TAG,"服务端返回："+Integer.toString(code));
                    new MessageToUi().send(23,"exception","服务端返回："+Integer.toString(code),handler0);

                }
            }catch (Exception e)
            {
                waitDialog.dismiss();
                Log.e(TAG, "HTTP request err......");
                e.printStackTrace();
                new MessageToUi().send(23,"exception",e.toString(),handler0);
            }

        }

    }


    //自定义handler类
    class WorkerProductInfoHandler extends Handler {
        @Override
        //接收别的线程的信息并处理
        public void handleMessage(Message msg) {
            Log.i("WorkerProductInfo",Integer.toString(msg.arg1));

            try {
                if (onDetach != false)

                    return;

                    switch (msg.arg1) {
                    case 1:
                    {
                        Bundle bundle1=msg.getData();
                        String info = bundle1.getString("info");
                        MyToast.showLongToast(context,info);
                        addTableLayoutView();
                    }
                        break;
                    case 2:

                        break;
                    case 3:
                        break;
                    case 23:
                    {
                        Bundle bundle23=msg.getData();
                        String info = bundle23.getString("exception");
                        MyToast.showToast(context,info);
                    }
                    break;
                    case 444:
                    {
                        Bundle bundle444=msg.getData();
                        String info = bundle444.getString("exception");
                        MyToast.showToast(context,info);

                    }
                    break;

                    default:
                        break;
                }
            }catch (Exception e)
            {
                e.printStackTrace();
                MyToast.showToast(context,e.toString());
            }
        }
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        onDetach = true;
        unbinder.unbind();
    }


}
